//
//  MarketWatchTableViewController.m
//  bondwatch_purecode
//
//  Created by Jason Yuan on 5/26/15.
//  Copyright (c) 2015 Sumridge. All rights reserved.
//

#import "MarketWatchTableViewController.h"
#import "MarketDetailTableViewController.h"
#import "AddMarketWatchViewController.h"

@interface MarketWatchTableViewController ()
{
    NSMutableArray *dataArray;
}

@end

@implementation MarketWatchTableViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.title = @"Watch List";
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
        [UIFont fontWithName:@"Helvetica-Bold" size:18.0],NSFontAttributeName, nil]];
    
    UIBarButtonItem *settingBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Settings"] style:UIBarButtonItemStylePlain target:self action:@selector(settingBarButtonItemPressed:)];
    self.navigationItem.leftBarButtonItem = settingBarButton;
    
    UIBarButtonItem *refreshBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Refresh"] style:UIBarButtonItemStylePlain target:self action:@selector(refreshBarButtonPressed:)];
    
    UIBarButtonItem *addBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Add"] style:UIBarButtonItemStylePlain target:self action:@selector(addBarButtonItemPressed:)];
    
    NSArray *rightBarButtonArray = @[refreshBarButton, addBarButton];
    self.navigationItem.rightBarButtonItems = rightBarButtonArray;
    
    self.tableView.separatorInset = UIEdgeInsetsZero;
    self.tableView.layoutMargins = UIEdgeInsetsZero;
    
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [self.tableView setTableFooterView:view];
}

- (void)settingBarButtonItemPressed:(id)sender {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)addBarButtonItemPressed:(id)sender {
    AddMarketWatchViewController *addMarketWatchViewController = [[AddMarketWatchViewController alloc] init];
    [self.navigationController pushViewController:addMarketWatchViewController animated:YES];
}

- (void)refreshBarButtonPressed:(id)sender {
    [self getData];
}

- (void)getData {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 100.0f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager GET:MARKETWATCHURL parameters:nil success:^(NSURLSessionDataTask *task, id JSON) {
        NSString *string = [[NSString alloc] initWithData:JSON encoding:NSUTF8StringEncoding];
        NSDictionary *dictionary = [string objectFromJSONString];
        DDLogVerbose(@"Watchlist data is:\n%@", dictionary);
        dataArray =  [NSMutableArray arrayWithArray:[dictionary objectForKey:@"data"]] ;
        [Shared shared].listArray = dataArray;
        [self.tableView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        if (response.statusCode == 200) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            return;
        }
        
        DDLogError(@"Get watchlist error:\n%@", error);
        NSString *result = [[NSString alloc] initWithData:[error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
        DDLogError(@"Get watchlist error reson:\n%@", result);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (dataArray != nil) {
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        return [dataArray count];
    } else {
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 36.0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MarketWatch"];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"MarketWatch"];
        cell.separatorInset = UIEdgeInsetsZero;
        cell.layoutMargins = UIEdgeInsetsZero;
    }
    
    NSDictionary *data = [dataArray objectAtIndex:[indexPath row]];
    
    cell.textLabel.text = [data objectForKey:@"prwName"];
    cell.textLabel.textColor = SUMRIDGECOLOR;
//    cell.detailTextLabel.text = [[data objectForKey:@"cusipNums"] stringValue];
    
    return cell;
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.row];
        NSString *prwId = [dictionary objectForKey:@"prwId"];
        NSDictionary *params = @{@"prwId": prwId};
        [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:DELETELISTURL]];
        [request setHTTPMethod:@"POST"];
        
        [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
        NSMutableData *postBody = [NSMutableData data];
        [postBody appendData:[params JSONData]];
        [request setHTTPBody:postBody];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
        operation.responseSerializer = [AFHTTPResponseSerializer serializer];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
#if DEBUGMODE
            LoggerApp(1, @"%@", result);
#endif
            NSDictionary *dictionary = [result objectFromJSONString];
            NSNumber *success = [dictionary objectForKey:@"success"];
            if ([success intValue] == 1) {
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = [NSString stringWithFormat:@"Delete Group(%@) successfully.", [dictionary objectForKey:@"prwName"]] ;
                
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    // Do something...
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                });
                [dataArray removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            } else {
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = [NSString stringWithFormat:@"Delete Group(%@) failure.", [dictionary objectForKey:@"prwName"]] ;
                hud.detailsLabelText = @"Please try again";
                
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    // Do something...
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                });
            }
        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
#if DEBUGMODE
            LoggerApp(1, @"%@", error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
#endif
        }];
        [[NSOperationQueue mainQueue] addOperation:operation]; 
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *data = [dataArray objectAtIndex:[indexPath row]];
    [Shared shared].prwId = [data objectForKey:@"prwId"];
    [Shared shared].prwName = [data objectForKey:@"prwName"];
    
    MarketDetailTableViewController *marketDetailTableViewController = [[MarketDetailTableViewController alloc] init];
    [self.navigationController pushViewController:marketDetailTableViewController animated:YES];
}

#pragma mark - Setting Rotate

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

@end
